package cn.school.student.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.school.basics.dao.BaseSpaceLocationDao;
import cn.school.basics.dao.BaseSubjectDao;
import cn.school.basics.dao.DormitoryBerthDao;
import cn.school.basics.vo.BaseSpaceLocationVO;
import cn.school.basics.vo.BaseSubjectVO;
import cn.school.basics.vo.DormitoryBerthVO;
import cn.school.classManage.dao.SchoolClassDao;
import cn.school.classManage.vo.SchoolClassVO;
import cn.school.common.IdWorker;
import cn.school.common.api.CommonPage;
import cn.school.common.api.CommonResult;
import cn.school.common.exception.ApiException;
import cn.school.common.rabbitMQ.RabbitSenderService;
import cn.school.common.utils.*;
import cn.school.pay.dao.StudentChargeRelationDao;
import cn.school.pay.vo.StudentChargeRelationVO;
import cn.school.student.dao.StudentInfoDao;
import cn.school.student.entity.StudentInfo;
import cn.school.student.entity.StudentPictureInfo;
import cn.school.student.entity.vo.*;
import cn.school.student.param.StudentInfoPageParam;
import cn.school.student.param.StudentQueryByClassDTO;
import cn.school.student.service.StudentInfoService;
import cn.school.student.vo.StudentContactsImportVO;
import cn.school.sys.entity.SysConfig;
import cn.school.sys.entity.SysUser;
import cn.school.sys.service.OnlineUserService;
import cn.school.sys.service.SysConfigService;
import cn.school.tencent.service.TencentCosFileService;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.SyncReadListener;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.xssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class StudentInfoServiceImpl extends ServiceImpl<StudentInfoDao, StudentInfo> implements StudentInfoService {
    private Logger log = LoggerFactory.getLogger(StudentInfoServiceImpl.class);
    @Autowired
    SchoolClassDao classDao;
    @Autowired
    StudentInfoDao studentInfoDao;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private JwtTokenUtil jwtTokenUtil;
    @Resource
    private OnlineUserService onlineUserService;


    @Resource
    private BaseSubjectDao baseSubjectDao;
    @Resource
    private StudentChargeRelationDao studentChargeRelationDao;

    @Resource
    private BaseSpaceLocationDao baseSpaceLocationDao;

    @Resource
    private DormitoryBerthDao dormitoryBerthDao;

    @Value("${student.picturePathDir}")
    private String filePath;

    @Resource
    private RabbitSenderService rabbitSenderService;

    @Autowired
    private TencentCosFileService tencentCosFileService;

    @Autowired
    private SysConfigService sysConfigService;


    @Override
    public CommonResult<Long> enterStudent(StudentInfo studentInfo) {
        LambdaQueryWrapper<StudentInfo> wrapper = new LambdaQueryWrapper<>();
        //自动生成唯一学号
        IdWorker snowFlake = new IdWorker(30, 30);
        studentInfo.setStudentId(String.valueOf(snowFlake.nextId()));
        wrapper.eq(StudentInfo::getTenantId, SysUserUtils.getSysUser().getTenantId());
        wrapper.eq(StudentInfo::getStudentId, studentInfo.getStudentId());
        int count = this.baseMapper.selectCount(wrapper);
        if (count > 0) {
            return CommonResult.failed("学号重复，请修改后提交");
        }
        studentInfo.setCreateBy(SysUserUtils.getSysUser().getUsername());
        studentInfo.setTenantId(SysUserUtils.getSysUser().getTenantId());
        studentInfo.setCreateTime(new Date());
        studentInfo.setStatus("1");//添加默认为有效的
        studentInfo.setPassword(passwordEncoder.encode("12345678"));

        int num = this.baseMapper.insert(studentInfo);
        //添加学生的收费项目
        if (studentInfo.getScRelationList() != null && studentInfo.getScRelationList().size() > 0) {
            StudentChargeRelationVO vo = null;
            for (String str : studentInfo.getScRelationList()) {
                vo = new StudentChargeRelationVO();
                vo.setStudentId(studentInfo.getId() + "");
                vo.setChargeId(str);
                vo.setTenantId(SysUserUtils.getSysUser().getTenantId());
                studentChargeRelationDao.insert(vo);
            }
        }

        if (num > 0) {

            return CommonResult.success(studentInfo.getId());
        }
        return CommonResult.failed();
    }

    @Override
    public CommonResult<CommonPage<StudentInfo>> getStudentInfoPage(StudentInfoPageParam studentInfoPageParam) {
        SysUser sysUser = SysUserUtils.getSysUser();
        boolean isClassTeacher = sysUser.getRoleInfoList().stream().anyMatch(m -> m.getRoleName().equals("班主任"));
        if (isClassTeacher) {
            studentInfoPageParam.setIsClassTeacher("yes");
            studentInfoPageParam.setTeacherId(sysUser.getUsername());
        }

        int count = this.baseMapper.queryCount(studentInfoPageParam);
        List<StudentInfo> studentInfoList = this.baseMapper.queryLimit(studentInfoPageParam);
        IPage<StudentInfo> studentInfoPage = new Page<>();
        studentInfoPage.setTotal(count);
        studentInfoPage.setSize(studentInfoPageParam.getPageSize());
        studentInfoPage.setCurrent(studentInfoPageParam.getPageNum());
        studentInfoPage.setRecords(studentInfoList);
        return CommonResult.success(CommonPage.restPage(studentInfoPage));
    }

    @Override
    public CommonResult<Integer> deleteStudentInfo(Long id) {
        if (this.baseMapper.deleteById(id) > 0) {
            return CommonResult.success();
        }
        return CommonResult.failed();
    }

    @Override
    public CommonResult<Integer> updateStudent(StudentInfo studentInfo) {
        LambdaQueryWrapper<StudentInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.ne(StudentInfo::getId, studentInfo.getId());
        wrapper.eq(StudentInfo::getStudentId, studentInfo.getStudentId());
        int count = this.baseMapper.selectCount(wrapper);
        if (count > 0) {
            return CommonResult.failed("学号重复，请修改后提交");
        }

        studentInfo.setModifyBy(SysUserUtils.getSysUser().getUsername());
        studentInfo.setModifyTime(new Date());

        //添加学生的收费项目
        if (studentInfo.getScRelationList() != null && studentInfo.getScRelationList().size() > 0) {
            LambdaQueryWrapper<StudentChargeRelationVO> scWrapper = new LambdaQueryWrapper<>();
            scWrapper.eq(StudentChargeRelationVO::getStudentId, studentInfo.getId());
            studentChargeRelationDao.delete(scWrapper);
            StudentChargeRelationVO vo = null;
            for (String str : studentInfo.getScRelationList()) {
                vo = new StudentChargeRelationVO();
                vo.setStudentId(studentInfo.getId() + "");
                vo.setChargeId(str);
                studentChargeRelationDao.insert(vo);
            }
        }
        if (this.baseMapper.update(studentInfo) > 0) {
            return CommonResult.success();
        }
        return CommonResult.failed();
    }



    @Override
    public CommonResult<Integer> updateBatchStudent(List<StudentInfo> list) {
        int num = 0;
        for (StudentInfo studentInfo : list) {
            studentInfo.setModifyBy(SysUserUtils.getSysUser().getUsername());
            studentInfo.setModifyTime(new Date());
            this.baseMapper.updateById(studentInfo);
            num++;
        }

        if (num > 0) {
            return CommonResult.success();
        }
        return CommonResult.failed();
    }


    @Override
    public CommonResult<StudentInfo> getStudentInfoById(Long id) {
        StudentInfo studentInfo = this.baseMapper.selectById(id);
        LambdaQueryWrapper<StudentChargeRelationVO> studentInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        studentInfoLambdaQueryWrapper.eq(StudentChargeRelationVO::getStudentId, id);
        List<StudentChargeRelationVO> voList = studentChargeRelationDao.selectList(studentInfoLambdaQueryWrapper);
        List<String> rList = new ArrayList<>();
        for (StudentChargeRelationVO vo : voList) {
            rList.add(vo.getChargeId());
        }
        studentInfo.setScRelationList(rList);
        return CommonResult.success(studentInfo);
    }

    @Override
    @Transactional
    public CommonResult<Integer> importStudentInfoFromExcel(MultipartFile multipartFile) throws IOException, ApiException {

        System.out.println("开始解析excel....");
        long start = System.currentTimeMillis();
        //当前登录用户
        String username = SysUserUtils.getSysUser().getUsername();
        List<StudentInfo> readList = new ArrayList<>();
        try {
            EasyExcel.read(multipartFile.getInputStream(), StudentInfo.class, new SyncReadListener() {
                //EasyExcel在读取excel表格时，每读取到一行，就会调用一次这个方法
                @Override
                public void invoke(Object object, AnalysisContext context) {
                    //读取到的数据被存入bean
                    StudentInfo studentInfo = (StudentInfo) object;
                    if (StringUtils.isEmpty(studentInfo.getName())) {
                        throw new ExcelAnalysisException("缺少必填内容");
                    }
                    //自动生成唯一学号
                    IdWorker snowFlake = new IdWorker(30, 30);
                    studentInfo.setStudentId(String.valueOf(snowFlake.nextId()));
                    studentInfo.setPassword(passwordEncoder.encode("12345678"));
                    studentInfo.setCreateBy(username);
                    studentInfo.setStatus("1");
                    studentInfo.setTenantId(SysUserUtils.getSysUser().getTenantId());
                    readList.add(studentInfo);
                }
            }).doReadAll();
        } catch (ExcelAnalysisException e) {
            return CommonResult.failed(e.getMessage());
        }

        long end = System.currentTimeMillis();
        System.out.println("结束解析excel,共耗时:" + (end - start) / 1000);

        System.out.println("开始插入数据至数据库.");
        long startInsert = System.currentTimeMillis();
        Map<String, String> noMap = new HashMap<>();
        Map<String, String> studentIdMap = new HashMap<>();

        for (StudentInfo info : readList) {
            noMap.put(info.getStudentId(), info.getStudentId());
            if (Objects.nonNull(info.getId())) {
                studentIdMap.put(String.valueOf(info.getId()), String.valueOf(info.getId()));
            }
        }
        List<String> noList = new ArrayList<String>(noMap.keySet());
        List<String> studentIdList = new ArrayList<>(studentIdMap.keySet());

        LambdaQueryWrapper<StudentInfo> noQuery = new LambdaQueryWrapper<>();
        noQuery.in(StudentInfo::getStudentId, noList);
        noQuery.eq(StudentInfo::getTenantId, SysUserUtils.getSysUser().getTenantId());
        List<StudentInfo> noStudentList = studentInfoDao.selectList(noQuery);
        if (CollectionUtil.isNotEmpty(noStudentList)) {
            return CommonResult.failed("学号为:" + noStudentList.stream().map(StudentInfo::getStudentId).collect(Collectors.joining(",")) + "的学生学号已存在");
        }

        if (CollectionUtil.isNotEmpty(studentIdList)) {
            // 如果有学生id重复的数据，则更新学生信息
            LambdaQueryWrapper<StudentInfo> studentIdQuery = new LambdaQueryWrapper<>();
            studentIdQuery.in(StudentInfo::getId, studentIdList);
            studentIdQuery.eq(StudentInfo::getTenantId, SysUserUtils.getSysUser().getTenantId());
            List<StudentInfo> studentRepeatIdList = studentInfoDao.selectList(studentIdQuery);

            if (CollectionUtil.isNotEmpty(studentRepeatIdList)) {
                for (StudentInfo studentInfo : studentRepeatIdList) {
                    studentInfoDao.update(studentInfo);
                }
                // 去除掉重复Id的数据
                readList.removeAll(studentRepeatIdList);
            }
        }




   /*     int cardIdcount = studentInfoDao.findCardIdExists(cardIdList);
        if(cardIdcount>0){
            return CommonResult.failed("身份证号码重复");
        }
        int noCount = studentInfoDao.findStudentIdExists(noList);
        if(noCount>0){
            return CommonResult.failed("学号重复");
        }
        int count = studentInfoDao.findPhoneExists(phoneList);
        if(count>0){
            return CommonResult.failed("手机号码重复");
        }*/


        if (readList.size() == 0) {
            return CommonResult.failed("没有可导入的数据");
        }

        // 导入学生数据
        for (StudentInfo studentInfo : readList) {
            int insert = studentInfoDao.insert(studentInfo);
            if (insert < 1) {
                return CommonResult.failed("插入学生数据:" + studentInfo.getName() + "失败，请练习管理员。");
            }
        }
        long endInsert = System.currentTimeMillis();
        System.out.println("插入数据执行完成.共耗时:" + (endInsert - startInsert) / 1000);
        return CommonResult.success();
    }

    @Override
    public IPage<StudentInfo> findStudentInfoByClass(StudentQueryByClassDTO queryDTO) {
        if (queryDTO.getClassId() == null) {
            SysUser sysUser = SysUserUtils.getSysUser();
            Long userId = sysUser.getId();
            QueryWrapper<SchoolClassVO> wrapper = new QueryWrapper<>();
            wrapper.eq("class_teacher_id", userId);
            List<SchoolClassVO> classList = classDao.selectList(wrapper);
            List<Long> classIdList = new ArrayList<>();
            classList.forEach(item -> {
                classIdList.add(item.getId());
            });
            QueryWrapper<StudentInfo> stuWrapper = new QueryWrapper<>();
            stuWrapper.in("class_id", classIdList);
            Page<StudentInfo> page = page(new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize()), stuWrapper);
            return page;
        } else {
            QueryWrapper<StudentInfo> stuWrapper = new QueryWrapper<>();
            stuWrapper.eq("class_id", queryDTO.getClassId());
            return page(new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize()), stuWrapper);
        }
    }

    @Override
    public String login(String username, String password, HttpServletRequest request) {
        String token = null;
        //密码需要客户端加密后传递
        try {
            LambdaQueryWrapper<StudentInfo> studentInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            studentInfoLambdaQueryWrapper.eq(StudentInfo::getPhone, username);
            StudentInfo studentInfo = this.getOne(studentInfoLambdaQueryWrapper);
            if (studentInfo == null) {
                throw new BadCredentialsException("用户不存在");
            }
            if ("0".equals(studentInfo.getEnabled())) {
                throw new BadCredentialsException("账号限制登录");
            }

            StudentInfoDetails userDetails = new StudentInfoDetails(studentInfo);
            if (!passwordEncoder.matches(password, userDetails.getPassword())) {
                throw new BadCredentialsException("密码不正确");
            }
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            token = jwtTokenUtil.generateToken(userDetails.getUsername());
            StudentInfo studentInfoLogin = SysUserUtils.getStudentUser();
            // 保存在线信息
            onlineUserService.saveAppStudent(studentInfoLogin, token, jwtTokenUtil.getExpiration(), request);

            boolean singleLogin = false;

            if (singleLogin) {
                //踢掉之前已经登录的token
                onlineUserService.checkAppStudentLoginOnUser(studentInfoLogin.getPhone(), token);
            }
        } catch (AuthenticationException e) {
            throw e;
        } finally {
            return token;
        }
//        return token;
    }

    @Override
    public UserDetails loadStudentInfoByPhone(String phone) {
        LambdaQueryWrapper<StudentInfo> studentInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        studentInfoLambdaQueryWrapper.eq(StudentInfo::getPhone, phone);
        StudentInfo studentInfo = this.getOne(studentInfoLambdaQueryWrapper);
        if (studentInfo == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        StudentInfoDetails userDetails = new StudentInfoDetails(studentInfo);
        return userDetails;
    }

    @Override
    public UserDetails loadParentInfoByPhone(String phone) {
        LambdaQueryWrapper<StudentInfo> studentInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        studentInfoLambdaQueryWrapper.eq(StudentInfo::getGuardianPhoneNumber, phone);
        List<StudentInfo> studentParentInfoList = this.list(studentInfoLambdaQueryWrapper);
        StudentInfo parentInfo = new StudentInfo();
        if (studentParentInfoList != null && studentParentInfoList.size() != 0) {
            parentInfo = studentParentInfoList.get(0);
        }
        if (parentInfo == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        ParentUserInfoDetails userDetails = new ParentUserInfoDetails(parentInfo);
        return userDetails;
    }

    @Override
    public int updatePasswordByStudentId(Long id, String newPass) {
        StudentInfo studentInfo = this.baseMapper.selectById(id);
        if (studentInfo == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        studentInfo.setPassword(newPass);
        int update = this.baseMapper.updateById(studentInfo);
        return update;
    }

    @Override
    public void resetPwd(Long id) {
        String resetPwd = passwordEncoder.encode("12345678");
        StudentInfo studentInfo = this.baseMapper.selectById(id);
        if (studentInfo == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        studentInfo.setPassword(resetPwd);
        this.baseMapper.updateById(studentInfo);
    }

    @Override
    public void parentResetPwd(Long id) {
        StudentInfo studentInfo = this.baseMapper.selectById(id);
        if (studentInfo == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        if (StringUtils.isEmpty(studentInfo.getGuardianPhoneNumber())) {
            throw new UsernameNotFoundException("该用户还未注册");
        }
        LambdaQueryWrapper<StudentInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StudentInfo::getGuardianPhoneNumber, studentInfo.getGuardianPhoneNumber());
        List<StudentInfo> studentInfos = baseMapper.selectList(queryWrapper);
        batchResetParentsPwd(studentInfos);
    }

    @Override
    public List<SchoolClassVO> allSchoolClass() {
        return classDao.selectAll();
    }

    @Override
    public String findTuitionFeeByClassId(Long classId) {
        SchoolClassVO classVO = classDao.selectById(classId);
        String subjectId = classVO.getClassSubject();
        if (Objects.isNull(classVO.getClassSubject())) {
            return "0";
        }
        BaseSubjectVO subjectVO = baseSubjectDao.selectById(subjectId);
        if (Objects.isNull(subjectVO)) {
            return "0";
        }
        return String.valueOf(subjectVO.getSubjectAmount() == null ? "0" : subjectVO.getSubjectAmount());
    }

    @Override
    public int updateStudentInfo(StudentInfo info) {
        return baseMapper.updateById(info);
    }

    @Override
    public String loginByParentUser(String username, String password, HttpServletRequest request) {
        String token = null;
        //密码需要客户端加密后传递
        try {
            LambdaQueryWrapper<StudentInfo> studentInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            studentInfoLambdaQueryWrapper.eq(StudentInfo::getGuardianPhoneNumber, username);
            studentInfoLambdaQueryWrapper.eq(StudentInfo::getStatus, "1");
            List<StudentInfo> studentParentInfoList = this.list(studentInfoLambdaQueryWrapper);
            StudentInfo studentParentInfo = null;
            if (studentParentInfoList != null && studentParentInfoList.size() != 0) {
                studentParentInfo = studentParentInfoList.get(0);
                if ("0".equals(studentParentInfo.getEnabled())) {
                    throw new BadCredentialsException("账号被限制登录");
                }
            }
            if (studentParentInfo == null) {
                throw new BadCredentialsException("用户不存在");
            }
            ParentUserInfoDetails userDetails = new ParentUserInfoDetails(studentParentInfo);
            if (!passwordEncoder.matches(password, userDetails.getPassword())) {
                throw new BadCredentialsException("密码不正确");
            }
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            token = jwtTokenUtil.generateToken(userDetails.getUsername());
            StudentInfo studentInfoLogin = SysUserUtils.getParentUser();
            // 保存在线信息
            onlineUserService.saveAppParent(studentInfoLogin, token, jwtTokenUtil.getExpiration(), request);

            boolean singleLogin = false;

            if (singleLogin) {
                //踢掉之前已经登录的token
                onlineUserService.checkAppParentLoginOnUser(studentInfoLogin.getGuardianPhoneNumber(), token);
            }
        } catch (AuthenticationException e) {
            log.warn("登录异常:{}", e.getMessage());
        }
        return token;
    }

    @Override
    public int updatePasswordByParentId(Long id, String newPass) {
        StudentInfo studentInfo = this.baseMapper.selectById(id);
        if (studentInfo == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        if (StringUtils.isEmpty(studentInfo.getGuardianPhoneNumber())) {
            throw new UsernameNotFoundException("该用户还未注册");
        }
        LambdaQueryWrapper<StudentInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StudentInfo::getGuardianPhoneNumber, studentInfo.getGuardianPhoneNumber());
        List<StudentInfo> studentInfos = baseMapper.selectList(queryWrapper);
        studentInfos.forEach(stuInfo -> stuInfo.setGuardianPassword(newPass));
        return studentInfoDao.batchUpdateParentsPwd(studentInfos);
    }

    @Override
    public List<StudentInfoVo> queryList(ExamPublishParam examPublishParam) {
        return this.studentInfoDao.queryList(examPublishParam);
    }

    @Override
    public int deleteBatchStudentInfo(List<StudentInfo> list) {
        List<Long> ids = list.stream().map(StudentInfo::getId).collect(Collectors.toList());
        return studentInfoDao.deleteBatchIds(ids);
    }

    @Override
    public int batchResetStudentsPwd(List<StudentInfo> list) {
        list.forEach(studentInfo -> studentInfo.setPassword(passwordEncoder.encode("12345678")));
        return studentInfoDao.batchUpdateStudentsPwd(list);
    }

    @Override
    public int batchResetParentsPwd(List<StudentInfo> list) {
        list.forEach(studentInfo -> studentInfo.setGuardianPassword(passwordEncoder.encode("12345678")));
        return studentInfoDao.batchUpdateParentsPwd(list);
    }

    @Override
    public List<StudentInfo> getStudentInfosByClassIds(List<Long> classIds) {
        LambdaQueryWrapper<StudentInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(StudentInfo::getClassId, classIds);
        return studentInfoDao.selectList(queryWrapper);
    }

    @Override
    public List<StudentInfo> findStudentListByClassId(Long classId) {
        LambdaQueryWrapper<StudentInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StudentInfo::getClassId, classId);
        return studentInfoDao.selectList(queryWrapper);
    }

    @Override
    public List<StudentInfo> getClassInStudent(List<StudentContactsImportVO> list) {
        return null;
    }

    @Override
    public CommonResult<Integer> importStudentPictureExcel(MultipartFile multipartFile) throws IOException {


        return CommonResult.failed();
    }

    @Override
    public CommonResult<Integer> updateByStudentId(StudentInfo studentInfo) {
//        SchoolClassVO schoolClassVO = classDao.selectByClassId(studentInfo.getClassId());
//        studentInfo.setClassName(schoolClassVO.getClassName());
        SysUser user = SysUserUtils.getSysUser();
        studentInfo.setModifyBy(user.getUsername());
        studentInfo.setModifyTime(new Date());
        if (studentInfoDao.updateByStudentId(studentInfo) > 0) {
            return CommonResult.success();
        }
        return CommonResult.failed();
    }

    public List<StudentInfo> listByClass(String classId) {
        LambdaQueryWrapper<StudentInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StudentInfo::getClassId, classId);
        return this.baseMapper.selectList(queryWrapper);
    }

    @Override
    public StudentInfo getStudentInfo(String id) {
        return this.baseMapper.selectById(id);
    }


    public Map<String, XSSFPictureData> getPictures(XSSFSheet xssfSheet) {

        Map<String, XSSFPictureData> map = new HashMap<>();
        List<XSSFShape> list = xssfSheet.getDrawingPatriarch().getShapes();

        for (XSSFShape shape : list) {

            XSSFPicture picture = (XSSFPicture) shape;
            XSSFClientAnchor xssfClientAnchor = (XSSFClientAnchor) picture.getAnchor();
            XSSFPictureData pdata = picture.getPictureData();
            // 行号-列号
            String key = xssfClientAnchor.getRow1() + "-" + xssfClientAnchor.getCol1();
            log.info("key数据:{}", key);
            map.put(key, pdata);

        }

        return map;
    }


    @Override
    public List<DeviceStudentExcel> findStudentAll(StudentInfo studentInfo) {
        List<DeviceStudentExcel> deviceStudentExcels = this.studentInfoDao.studentByTenantIdList(SysUserUtils.getSysUser().getTenantId(), studentInfo);
        for (DeviceStudentExcel deviceStudentExcel : deviceStudentExcels) {
            if (!StringUtils.isEmpty(deviceStudentExcel.getImageName())) {
                String sourceImage = deviceStudentExcel.getImageName();
                if(!StringUtils.isEmpty(sourceImage)){
                    deviceStudentExcel.setImageName(sourceImage.substring(sourceImage.lastIndexOf("\\") + 1));
                }

            }

        }

        return deviceStudentExcels;
    }

    @Override
    public List<StudentInfoExcel> studentByTenantIdExportList(StudentInfo studentInfo) {
        return this.studentInfoDao.studentByTenantIdExportList(SysUserUtils.getSysUser().getTenantId(), studentInfo);

    }



    @Override
    public int studentRetreat(DormitoryBerthVO vo) {
//		DormitoryBerthVO dormitoryBerthVO = dormitoryBerthDao.selectById(vo.getId());
//		String useStudentId = dormitoryBerthVO.getUseStudentId();
        int num = dormitoryBerthDao.updateUseStudentIdIsNull(vo.getId());
        StudentInfo studentInfo = studentInfoDao.selectById(vo.getUseStudentId());
        studentInfo.setModifyTime(new Date());
        studentInfo.setModifyBy(SysUserUtils.getSysUser().getUsername());
        studentInfoDao.updateById(studentInfo);
        return num;
    }
}
